package com.bsoft.template.service.assets;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bsoft.template.common.Result;
import com.bsoft.template.common.auth.UserInfo;
import com.bsoft.template.entity.assets.AssetsLb;
import com.bsoft.template.entity.auth.User;
import com.bsoft.template.entity.system.Dic;
import com.bsoft.template.entity.system.DicDetails;
import com.bsoft.template.mapper.assets.AssetsLbMapper;
import com.bsoft.template.mapper.auth.UserMapper;
import com.bsoft.template.mapper.system.DicMapper;
import com.bsoft.template.service.base.BaseServiceImpl;
import com.bsoft.template.util.RequestParamPaser;
import com.bsoft.template.util.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AssetsLbService extends BaseServiceImpl<AssetsLbMapper, AssetsLb> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DicMapper dicMapper;

    @Autowired
    private UserInfo userInfo;

    public String getMaxId(String date) {
       return baseMapper.getMaxId(date);
    }

    public Result getExpire() {
        QueryWrapper<AssetsLb> wrapper = new QueryWrapper<>();
        wrapper.eq("zt", "02");
        List<AssetsLb> list = baseMapper.selectList(wrapper);
        Date current = new Date();
        long num = list.stream().filter(item -> (item.getHtjsrq().getTime() - current.getTime()) / (1000 * 60 * 60 * 24) <= 30
                && item.getHtjsrq().getTime() - current.getTime() >= 0)
                .collect(Collectors.groupingBy(item -> item.getCfd() + item.getFjh()))
                .size();
        return new Result().ok().data(num);
    }

    public Result getAuditCount() {
        String role = userInfo.getRoleCode();
        long count = 0;

        if ("zhixing".equals(role)) {
            QueryWrapper<AssetsLb> wrapper = new QueryWrapper<>();
            wrapper.eq("zt", "01");
            count = baseMapper.selectCount(wrapper);
        }

        if ("fuzong".equals(role)) {
            QueryWrapper<AssetsLb> wrapper = new QueryWrapper<>();
            wrapper.eq("zt", "05");
            count = baseMapper.selectCount(wrapper);
        }

        return new Result().ok().data(count);
    }

    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String fjh = request.getParameter("fjh");
        String cfd = request.getParameter("cfd");

        if (StringUtils.isAnyBlank(fjh, cfd)) {
            return;
        }

        QueryWrapper<AssetsLb> wrapper = new QueryWrapper<>();
        wrapper.eq("cfd", cfd)
                .eq("fjh", fjh)
                .orderByDesc("zdrq");
        List<AssetsLb> assetsLbs = baseMapper.selectList(wrapper);

        List<User> users = userMapper.getAllUser();
        List<Dic> dics = dicMapper.getAllDic();

        Map<String, Object> userDic = new HashMap<>();
        for (User user : users) {
            if (user.getPerson() != null) {
                userDic.put(user.getUsername(), user.getPerson().getPersonName());
            } else {
                userDic.put(user.getUsername(), "");
            }

        }

        Map<String, Object> lbDic = new HashMap<>();
        Map<String, List<DicDetails>> mcDic = new HashMap<>();
        for (Dic dic : dics) {
            lbDic.put(dic.getCode(), dic.getName());
            mcDic.put(dic.getCode(), dic.getDicDetails());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

        List<Map<String,  Object>> list = new ArrayList<>();
        for (AssetsLb assetsLb : assetsLbs) {
            Map<String, Object> item = new HashMap<>();
            item.put("mc", mcDic.get(assetsLb.getZclb()).stream().filter(i -> i.getKey().equals(assetsLb.getMc()))
                    .findFirst().get().getLabel());
            item.put("pp", assetsLb.getPp());
            item.put("ggxh", assetsLb.getGgxh());
            item.put("ccrq", assetsLb.getCcrq() != null ? sdf.format(assetsLb.getCcrq()) : "");
            item.put("gmrq", assetsLb.getGmrq() != null ? sdf.format(assetsLb.getGmrq()) : "");
            item.put("synx", assetsLb.getSynx());
            item.put("sl", assetsLb.getSl());
            item.put("cfd", lbDic.get(assetsLb.getCfd()));
            item.put("fjh", mcDic.get(assetsLb.getCfd()).stream().filter(i -> i.getKey().equals(assetsLb.getFjh()))
                    .findFirst().get().getLabel());
            item.put("htqx", sdf.format(assetsLb.getHtksrq()) + "-" + sdf.format(assetsLb.getHtjsrq()));
            item.put("dwfzr", userDic.get(assetsLb.getDwfzr()));
            item.put("jbr", userDic.get(assetsLb.getJbr()));
            item.put("zdrq", sdf.format(assetsLb.getZdrq()));
            item.put("zdr", userDic.get(assetsLb.getZdr()));
            item.put("bz", assetsLb.getBz());
            list.add(item);
        }

        ExcelWriter excelWriter = ExcelUtil.writeExcel(response, "龙宝大厦用表.xlsx", "龙宝大厦用表", ExcelTypeEnum.XLSX);
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        Map<String, Object> map = list.get(0);
        map.put("zdr", list.stream().map(i -> String.valueOf(i.get("zdr"))).collect(Collectors.toSet()).stream().collect(Collectors.joining(",")));
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }

    public void exportExcelAll(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Map<String, String> params = RequestParamPaser.getParameters(request);
        QueryWrapper<AssetsLb> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(params.get("pzh"))) {
            wrapper.like("pzh", params.get("pzh"));
        }
        if (StringUtils.isNotBlank(params.get("zclb"))) {
            wrapper.eq("zclb", params.get("zclb"));
        }
        if (StringUtils.isNotBlank(params.get("mc"))) {
            wrapper.eq("mc", params.get("mc"));
        }
        if (StringUtils.isNotBlank(params.get("cfd"))) {
            wrapper.eq("cfd", params.get("cfd"));
        }
        if (StringUtils.isNotBlank(params.get("fjh"))) {
            wrapper.eq("fjh", params.get("fjh"));
        }
        List<AssetsLb> assetsLbs = baseMapper.selectList(wrapper);

        List<User> users = userMapper.getAllUser();
        List<Dic> dics = dicMapper.getAllDic();

        Map<String, Object> userDic = new HashMap<>();
        for (User user : users) {
            if (user.getPerson() != null) {
                userDic.put(user.getUsername(), user.getPerson().getPersonName());
            } else {
                userDic.put(user.getUsername(), "");
            }

        }

        Map<String, Object> lbDic = new HashMap<>();
        Map<String, List<DicDetails>> mcDic = new HashMap<>();
        for (Dic dic : dics) {
            lbDic.put(dic.getCode(), dic.getName());
            mcDic.put(dic.getCode(), dic.getDicDetails());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

        List<Map<String,  Object>> list = new ArrayList<>();
        for (AssetsLb assetsLb : assetsLbs) {
            Map<String, Object> item = new HashMap<>();
            item.put("pzh", assetsLb.getPzh());
            item.put("mc", mcDic.get(assetsLb.getZclb()).stream().filter(i -> i.getKey().equals(assetsLb.getMc()))
                    .findFirst().get().getLabel());
            item.put("zclb", lbDic.get(assetsLb.getZclb()));
            item.put("pp", assetsLb.getPp());
            item.put("ggxh", assetsLb.getGgxh());
            item.put("ccrq", assetsLb.getCcrq() != null ? sdf.format(assetsLb.getCcrq()) : "");
            item.put("gmrq", assetsLb.getGmrq() != null ? sdf.format(assetsLb.getGmrq()) : "");
            item.put("synx", assetsLb.getSynx());
            item.put("sl", assetsLb.getSl());
            item.put("cfd", lbDic.get(assetsLb.getCfd()));
            item.put("fjh", mcDic.get(assetsLb.getCfd()).stream().filter(i -> i.getKey().equals(assetsLb.getFjh()))
                    .findFirst().get().getLabel());
            item.put("dwfzr", userDic.get(assetsLb.getDwfzr()));
            item.put("jbr", userDic.get(assetsLb.getJbr()));
            item.put("zdrq", sdf.format(assetsLb.getZdrq()));
            item.put("zdr", userDic.get(assetsLb.getZdr()));
            item.put("bz", assetsLb.getBz());
            list.add(item);
        }

        ExcelWriter excelWriter = ExcelUtil.writeExcel(response, "龙宝大厦列表.xlsx", "龙宝大厦列表", ExcelTypeEnum.XLSX);
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        excelWriter.finish();
    }
}
